﻿using System.Configuration;
using System.IO;
using System.Net;
using System.Xml;
using UpdaterComponents.Common;

namespace UpdaterComponents.Tasks
{
    public class UpdateDownloader : ITask
    {
        private string _Message;

        public UpdateDownloader()
        {
            _Message = "Downloading";
        }

        #region ITask Members

        public string Message
        {
            get { return _Message; }
            set { _Message = value; }
        }

        public void DoTask()
        {
            //Get the appname and compression type
            string sAppName = ConfigurationManager.AppSettings["ApplicationName"];

            DownloadUpdate(sAppName);
        }


        public void RollBack()
        {
            File.AppendAllText("UpgradeLog.txt", "Failed during download \n");
            string sUpdatesFile = ConfigurationManager.AppSettings["ReleasesXmlFile"];
            
            
            //Delete the NewRelase folder if prsesent
            if (Directory.Exists("NewRelease"))
                Directory.Delete("NewRelease", true);

            if (Directory.Exists(BackUpCreator.BackUpFolderName))
                Directory.Delete(BackUpCreator.BackUpFolderName, true);


            if (File.Exists(sUpdatesFile))
                File.Delete(sUpdatesFile);
        }

        #endregion

        private void DownloadUpdate(string sAppName)
        {
            string sUpdatesFile = ConfigurationManager.AppSettings["ReleasesXmlFile"];

            XmlDocument xmlDoc = new XmlDocument();


            xmlDoc.Load(sUpdatesFile);


            XmlNodeList nodes = xmlDoc.SelectNodes("//" + sAppName + "//File");

            if (!Directory.Exists("NewRelease"))
            {
                Directory.CreateDirectory("NewRelease");
            }


            foreach (XmlNode node in nodes)
            {
                XmlAttribute attr = node.Attributes["Path"];
                XmlAttribute nameattr = node.Attributes["Name"];


                string sURLToDownloadFile = attr.Value;
                string sName = nameattr.Value;
                string sDest = "NewRelease\\" + sName;
                //Create the directory tree 
               
                using (WebClient client = new WebClient())
                {

                    client.DownloadFile(sURLToDownloadFile, sDest);

                }
            }


        }
    }
}
